<?php
namespace app\serverfund\logic;

use \app\manage\logic\BaseLogic;
use \app\manage\service\ApiBase;

/**
 * @author:      李颖
 * @DateTime:    2017-11-10 10:14:35
 * @Description: 积分逻辑层
 */

class IntegralDistribute extends BaseLogic
{
    protected $integralDistributeValidate = '\app\serverfund\validate\IntegralDistribute';
    protected $integralDistributeLogic = '\app\serverfund\logic\IntegralDistribute';


    /*后台管理员进行一键积分派发（另写一个方法：根据各种查询条件获取证书不分页列表）*/
    //所需参数 1、证书ids（5个证书id） 2、distribute_time:  2017-11-10
    //流程思想：后台进行不断js请求接口，即该方法的功能为给5个证书进行积分派发操作
    //以每个证书为例进行执行流程：
    //1、获取积分派发比例  根据证书ids获取证书列表信息（不分页）  开始循环每个证书：
    //2、获取 “根据证书中的订单信息中的该证书商品的订单总价” 获取需要派发的积分个数
    //3、请求new-think方法“给5个证书进行派发积分”【自增证书累计收益+修改证书最后一次派发日期+添加一条证书派发记录】
    //4、和3同步请求new-think方法“给5个用户进行积分充值”
    //就算是取得3条没有证书去派发，也返回成功状态，以便后台进行循环调用
    public function oneKeyDistribute($data): array 
    {
        if(strtotime($data['distribute_time']) > NOW){
            return verify_err(null, '不能派发未来的');
        }
        //首先判断certificate_ids有没有超过3个证书
        if(count(explode(",", $data['certificate_ids'])) > 3){
            return verify_err($data['certificate_ids'], '一次性派发的证书的个数不能超过3个');
        }
    	//基本信息的获取
        $app_key = ApiBase::getAppKey();
        $getBase['query'] = json_encode([
            ['path'=>'serveruser/auth/Token/hGetAll', 'param'=>['token'=>$data['token']]],
            ['path'=>'serveruser/auth/App/find', 'param'=>['app_key'=>$app_key]],
            ['path'=>'servercertificate/certificate/Certificate/getCertiListByIds', 'param'=>['certificate_ids'=>$data['certificate_ids']]],
            ['path'=>'servercertificate/certificate/Certificate/getCertificateDistributeList', 'param'=>['certificate_ids'=>$data['certificate_ids'],'distribute_date'=>$data['distribute_time']]]
        ]);
        $baseInfo =  ApiBase::sendDataLots(config('proxy_all_url'), $getBase);
        if(!$baseInfo['res'][0] || !$baseInfo['res'][1] || !$baseInfo['res'][2]){
            return $baseInfo;
        }
        //获取积分派发比例
        $scale['query'] = json_encode([
            ['path'=>'serverfund/integral/IntegralDistribute/getOneNew', 'param'=>['app_id'=>$baseInfo['res'][1]['id']]]
        ]);
        $scaleRes = ApiBase::sendDataOne(config('proxy_all_url'), $scale);
        if($scaleRes['status'] != SUCCESS_STATUS){
            return $scaleRes;
        }
        /*判断这些证书是否具有积分派发的要求 是否超过最晚提货时间（跳过继续执行并提示） + 是否高级证书 + 是否已经派发（跳过继续执行并提示）+ 是否已提货 + 是否正在转让中 + 是否审核通过*/
        $readyDistribute = array_column($baseInfo['res'][3], 'certificate_id');
        $noDistributeMsg = $yesDistributeMsg = $distributeMsg = [];
        $certificateList = $baseInfo['res'][2];
        foreach ($certificateList as $k => &$v) {
            if($v['type'] != 'advanced'){ return verify_err(null, '请重新选择！证书【' . $v['name'] . '】不是高级证书'); }
            if($v['is_pick'] == 1){ return verify_err(null, '请重新选择！证书【' . $v['name'] . '】已提货'); }
            if($v['status'] != 1){ return verify_err(null, '请重新选择！证书【' . $v['name'] . '】状态不正常'); }
            //判断是否超过收益结束时间 是否派发过
            if($v['finish_distribute_time'] < strtotime($data['distribute_time'])){
                $errMsg = '【' . $data['distribute_time'] . '派发失败】原因：证书【' . $v['name'] . '】已超过收益结束时间';
                $noDistributeMsg[] = $errMsg;
                $v['isIntegralDistribute'] = 0;
                $v['remark'] = $errMsg;
            }elseif($v['create_time'] > strtotime($data['distribute_time'])){
                $errMsg = '【' . $data['distribute_time'] . '派发失败】原因：证书【' . $v['name'] . '】生成时间大于派发时间';
                $noDistributeMsg[] = $errMsg;
                $v['isIntegralDistribute'] = 0;
                $v['remark'] = $errMsg;
            }elseif($v['last_integral_distribute_date'] == $data['distribute_time'] || in_array($v['id'], $readyDistribute)){
                $errMsg = '【' . $data['distribute_time'] . '派发失败】原因：证书【' . $v['name'] . '】已派发过';
                $noDistributeMsg[] = $errMsg;
                $v['isIntegralDistribute'] = 0;
                $v['remark'] = $errMsg;
            }elseif($v['certificate_price'] < $scaleRes['res']['fund']){
                $errMsg = '【' . $data['distribute_time'] . '派发失败】原因：证书【' . $v['name'] . '】不够一个积分的派发';
                $noDistributeMsg[] = $errMsg;
                $v['isIntegralDistribute'] = 0;
                $v['remark'] = $errMsg;
            }else{   //成功
                $yesDistributeMsg[] = '【' . $data['distribute_time'] . '可以派发】证书【' . $v['name'] . '】可进行派发积分';
                $v['isIntegralDistribute'] = 1;
                $v['remark'] = '该证书符合派发条件';
            }
        }
        //封装数据请求 new-think方法“给5个证书进行派发积分”  new-think方法“给5个用户进行积分充值”
        $integralDistributeData['system_user_id'] = $baseInfo['res'][0]['id'];
        $integralDistributeData['system_user_name'] = $baseInfo['res'][0]['name'];
        $integralDistributeData['distribute_date'] = $data['distribute_time'];
        $yesDistributeInfo = $noDistributeInfo = [];
        $prepaidIntegral['update_ip'] = request()->ip();
        $prepaidIntegral['app_id'] = $baseInfo['res'][1]['id'];
        $prepaidIntegral['opposite_info'] = $baseInfo['res'][0];
        $prepaidUserInfos = [];
        foreach ($certificateList as $kk => $vv) {
            //整理证书的派发积分
            $goodsInfos = reset_array_key($vv['order_info']['goods_infos'], 'id');
            $final_price = $goodsInfos[$vv['goods_id']]['final_price'];
            $final_currency_price = $goodsInfos[$vv['goods_id']]['final_currency_price'];
            if($scaleRes['res']['fund_type'] == 'currency'){
                $integral = floor(bcdiv($final_currency_price, $scaleRes['res']['fund'], 4));
            }else{
                $integral = floor(bcdiv($final_price, $scaleRes['res']['fund'], 4));
            }
            
            $distributeInfo['certificate_user_id'] = $vv['user_id'];
            $distributeInfo['certificate_id'] = $vv['id'];
            $distributeInfo['certificate_name'] = $vv['name'];
            $distributeInfo['certificate_product_code'] = $vv['product_code'];
            $distributeInfo['integral'] = $integral;
            $distributeInfo['remark'] = $vv['remark'];
            $distributeInfo['rule_fund_type'] = $scaleRes['res']['fund_type'];
            $distributeInfo['rule_fund'] = $scaleRes['res']['fund'];
            $distributeInfo['rule_integral'] = $scaleRes['res']['integral'];
            if($vv['isIntegralDistribute'] == 1){
                //整理充值积分的账号
                $prepaidUser['id'] = $vv['user_id'];
                $prepaidUser['integral'] = $integral;
                if($integral > 0){
                    $prepaidUserInfos[] = $prepaidUser;
                    $yesDistributeInfo[] = $distributeInfo;
                }
            }else{
                $noDistributeInfo[] = $distributeInfo;
            }
        }
        //同时请求 new-think方法“给5个证书进行派发积分”  new-think方法“给5个用户进行积分充值”
        $integralDistributeData['yes_integral_distribute_info'] = $yesDistributeInfo;
        $integralDistributeData['no_integral_distribute_info'] = $noDistributeInfo;
        $prepaidIntegral['user_infos'] = $prepaidUserInfos;
        $integralDistributeQuery['query'] = json_encode([
            ['path'=>'servercertificate/certificate/Certificate/integralDistribute', 'param'=>$integralDistributeData],
            ['path'=>'serverfund/integral/IntegralAccount/prepaidByUids', 'param'=>$prepaidIntegral]
        ]);
        $integralDistributeRes = ApiBase::sendDataLots(config('proxy_queue_url'), $integralDistributeQuery);
        if($integralDistributeRes['status'] != SUCCESS_STATUS){
            return $integralDistributeRes;
        }
        $distributeMsg['success'] = $yesDistributeMsg;
        $distributeMsg['failure'] = $noDistributeMsg;
        return auto_success($distributeMsg, '成功给证书持有人派发积分');
    }

    public function add($data): array 
    {
        $app_key = ApiBase::getAppKey();
        $getBase['query'] = json_encode([
            ['path'=>'serveruser/auth/Token/hGetAll', 'param'=>['token'=>$data['token']]],
            ['path'=>'serveruser/auth/App/find', 'param'=>['app_key'=>$app_key]]
        ]);
        $baseInfo =  ApiBase::sendDataLots(config('proxy_all_url'), $getBase);
        if($baseInfo['status'] != SUCCESS_STATUS){
            return $baseInfo;
        }
        $data['app_id'] = $baseInfo['res'][1]['id'];
        $data['system_user_name'] = $baseInfo['res'][0]['name'];
        $addQuery['query'] = json_encode([
            ['path'=>'serverfund/integral/IntegralDistribute/add', 'param'=>$data]
        ]);
        return ApiBase::sendDataOne(config('proxy_queue_url'), $addQuery);
    }










}